<template>
  <div>
    <div class="searchInput">
      <input type="text" placeholder="请输入城市名或拼音"
             v-model="keyword"
      >
    </div>
    <div class="searchCity" ref="wrapper" v-show="keyword">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          class="border-bottom"
          @click="choiceCity(item.name)"
        >
          {{item.name}}
        </li>
        <li v-show="noData">没有找到相关信息</li>
      </ul>
    </div>
  </div>
</template>
<script>
  import BScroll from 'better-scroll'
export default {
    name: 'CitySearch',
    props: {
      cities: Object
    },
    data () {
      return {
        keyword: '',
        timer: null,
        list: []
      }
    },
    methods: {
      choiceCity (city) {
        this.$store.dispatch('changeCity', city)
        this.$router.push('/')
      }
    },
    mounted () {
      this.scroll = new BScroll(this.$refs.wrapper)
      this.scroll = new BScroll(this.$refs.wrapper, { mouseWheel: true, click: true, tap: true })
    },
    computed: {
      noData () {
        return !this.list.length
      }
    },
    watch: {
      keyword () {
        if (!this.keyword) {
          this.list = []
          return
        }
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.cities) {
            this.cities[i].forEach((value) => {
              if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                result.push(value)
              }
            })
          }
          this.list = result
          return this.list
        }, 100)
      }
    }
}
</script>
<style scoped>
  .searchInput {
    width: 100%;
    height: 35px;
    background-color: blue;
  }
  .searchInput input {
    margin-top: 4px;
    width: 94%;
    height: 26px;
    text-align: center;
    line-height: 30px;
    margin-left: 3%;
    border-radius: 4px;
    padding:0 26px;
    box-sizing: border-box;
    outline:none;
    boreder:0;
  }
  .searchCity {
    position: absolute;
    width: 100%;
    top: 95px;
    left: 0;
    bottom: 0;
    background-color: #cccccc;
    z-index: 1;
    overflow: hidden;
  }
  .searchCity ul li {
    line-height: 35px;
    padding-left: 5px;
    background-color: white;
  }
</style>
